package com.luke.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class EurekaClientController {

    public static Boolean SERVICE_STATE = true;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private Integer port;

    @GetMapping("/sayHello/{name}")
    public String sayHello(@PathVariable("name") String name){
        log.info("name:{}",name);
       /* try {
            TimeUnit.SECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        return "hello," + name+",from "+port;
    }

    @GetMapping("/setServiceState/{state}")
    public void setServiceState(@PathVariable("state") Boolean state) {
        SERVICE_STATE = state;
        log.info("修改服务当前运行状态，state:{}",state);
    }

    @GetMapping("/getInstanceList")
    public List<ServiceInstance> getInstanceList (){
        List<ServiceInstance> instanceList = new ArrayList<>();
        discoveryClient.getServices().forEach( serviceId -> {
            List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
            instanceList.addAll(instances);
        });
        return instanceList;
    }

}
